package kevin.framework.basic.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import kevin.framework.basic.common.ui.AjaxResult;
import kevin.framework.basic.common.ui.ClientButton;
import kevin.framework.basic.domain.User;
import kevin.framework.basic.domain.UserRole;
import kevin.framework.basic.service.IBaseService;
import kevin.framework.basic.service.IOrgService;
import kevin.framework.basic.service.IRoleService;
import kevin.framework.basic.service.IUserRoleService;
import kevin.framework.basic.service.IUserService;

/**
 * Generate by Kevin's CodeBuilder
 **/
@Controller
@RequestMapping(value = "/user")
public class UserController extends ResetfulBaseController<User, String> {

    @Resource(name = "roleService")
    IRoleService roleService;

    @Resource(name = "userRoleService")
    IUserRoleService userRoleService;

    IUserService userService;

    @Resource(name = "orgService")
    IOrgService orgService;

    @Resource(name = "userService")
    @Override
    public void setService(IBaseService<User, String> service) {
        this.service = service;
        userService = (IUserService)service;
    }

    /*
     * 页面 views/base/entityPath 文件夹路径
     * ***/
    @Override
    public String setPageModelPath(HttpServletRequest request) {
        // TODO Auto-generated method stub
        return "base" + File.separator + entityPath;
    }

    @Override
    protected void onRequestPage(String pageName, HttpServletRequest request) throws Exception {
        if ("form".equals(pageName) || "index".equals(pageName)) {
            JSONArray array = orgService.getOrgJsonByPid("0");
            request.setAttribute("orgJson", array);
        } else if ("role".equals(pageName)) {
            JSONArray rolesJson = roleService.getAvailabelRole();
            request.setAttribute("rolesJson", rolesJson);
            String userId = request.getParameter("userId");
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("userId", userId);
            request.setAttribute("userId", userId);
            List<UserRole> userRoles = userRoleService.selectParam(param);
            JSONArray array = JSONArray.parseArray(JSON.toJSONString(userRoles));
            request.setAttribute("userRoles", array);
        }
    }

    @RequestMapping(value = "/repasswd", method = RequestMethod.POST)
    public @ResponseBody AjaxResult repasswd(HttpServletRequest request) throws Exception {
        String userId = request.getParameter("userId");
        String newpwd = request.getParameter("newpwd");
        String needOldpwd = request.getParameter("needOldpwd");
        if (StringUtils.isNotEmpty(needOldpwd) && "true".equals(needOldpwd)) {
            String oldPwd = request.getParameter("oldpwd");
            User user = this.service.get(userId);
            String _pwd = DigestUtils.md5Hex(oldPwd);
            if (!_pwd.equals(user.getUserPwd())) {
                return returnFailData(getLang("user_pwd_diff"));
            }
        }
        Map<String, Object> updatePrs = new HashMap<String, Object>();
        updatePrs.put("userPwd", DigestUtils.md5Hex(newpwd));
        updatePrs.put("id", userId);
        this.service.updateParam(updatePrs);
        return returnSuccData(null);
    }

    @RequestMapping(value = "/roleUpdate", method = RequestMethod.POST)
    public @ResponseBody AjaxResult roleUpdate(HttpServletRequest request) throws Exception {
        String userId = request.getParameter("userId");
        String roleIds = request.getParameter("roleIds");
        String[] roles = new String[] {};
        if (StringUtils.isNotEmpty(roleIds)) {
            roles = roleIds.split(",");
        }
        userRoleService.saveUserRole(userId, roles);
        return returnSuccData(null);
    }

    @Override
    protected Map<String, Object> setListParams(HttpServletRequest request) throws Exception {

        Map<String, Object> prs = new HashMap<String, Object>();

        String nameAccount = request.getParameter("nameAccount");
        String orgId = request.getParameter("orgId");

        if (StringUtils.isNotEmpty(nameAccount)) {
            prs.put("nameAccount", nameAccount);
        }
        if (StringUtils.isNotEmpty(orgId)) {
            prs.put("orgId", orgId);
        }
        return prs;
    }

    @Override
    public void buttonCreateHanlder(User bean, ClientButton button) {
        if (bean != null && bean.getId().equals("0") && !button.getHandler().equals("pwdFn")) {
            button.setDisabled(true);
        }
    }

    @Override
    public AjaxResult delete(HttpServletRequest request) throws Exception {
        String idList = request.getParameter("idList");
        boolean isAdmin = false;
        if (idList.contains(",")) {
            String[] idTmpArr = idList.split(",");
            for (String id : idTmpArr) {
                if (id.equals("0")) {
                    isAdmin = true;
                    break;
                }
            }
        } else {// 单条数据删除
            if (idList.equals("0")) {
                isAdmin = true;
            }
        }
        if (isAdmin) {
            return returnFailData(getLang("user_opr_admin"));
        }
        return super.delete(request);
    }

    @Override
    public AjaxResult update(HttpServletRequest request) throws Exception {
        String id = request.getParameter("id");
        if (id.equals("0")) {
            return returnFailData(getLang("user_opr_admin"));
        }
        return super.update(request);
    }

    @Override
    public String saveFilter(User bean, boolean isupdate, HttpServletRequest request) {
        if (isupdate) {
            bean.setUserPwd(null);
        } else {
            String userPwd = bean.getUserPwd();
            String pwd = DigestUtils.md5Hex(userPwd);
            bean.setUserPwd(pwd);
        }
        return super.saveFilter(bean, isupdate, request);
    }

}
